<?php

declare(strict_types=1);

namespace App\Controller\Backend;

use App\Enum\LogTypeEnum;
use App\Utils\Helper\ControllerHelper;
use App\Utils\Helper\LogHelper;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\AdminBundle\Exception\ModelManagerException;
use Symfony\Component\HttpFoundation\Request;

final class PageAdminController extends ControllerHelper {

    protected function preEdit (Request $request, $object) {
        $response = parent::preEdit($request, $object);
        if ($response) {
            return $response;
        }
        if ($object->getStatus() === -1) {
            throw $this->createNotFoundException(sprintf('unable to find the object'));
        }
        return $this->verify($object);
    }

    protected function preDelete (Request $request, $object) {
        $response = parent::preDelete($request, $object);
        if ($response) {
            return $response;
        }
        if ($object->getStatus() === -1) {
            throw $this->createNotFoundException(sprintf('unable to find the object'));
        }
        return $this->verify($object);
    }

    public function deleteAction ($id) {
        if (Request::METHOD_DELETE === $this->getRestMethod()) {
            if ($this->isAppModeDemo()) {
                $this->addFlash('sonata_flash_error', 'Demo模式下禁止删除数据');
                return $this->redirectToList();
            }

            $request = $this->getRequest();
            $id = $request->get($this->admin->getIdParameter());
            $object = $this->admin->getObject($id);

            if (!$object) {
                throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
            }

            try {
                // 软删除文章
                $conn = $this->getDoctrine()->getConnection();
                $sql = 'UPDATE page SET status = -1 WHERE id = '.$object->getId();
                $stmt = $conn->prepare($sql);
                $stmt->execute();
                // 记录日志
                $description = '标题:['.$object->getTitle().'] ';
                LogHelper::buildLog(LogTypeEnum::TYPE_PAGE_DELETE, $description);
                $this->addFlash('sonata_flash_success', '成功删除');
            } catch (ModelManagerException $e) {
                $this->handleModelManagerException($e);
                $this->addFlash('sonata_flash_error', '删除失败');
            }
            return $this->redirectTo($object);
        } else {
            return parent::deleteAction($id);
        }
    }

    public function batchActionDelete (ProxyQueryInterface $query) {
        try {
            if ($this->isAppModeDemo()) {
                $this->addFlash('sonata_flash_error', 'Demo模式下禁止批量删除数据');
                return $this->redirectToList();
            }

            $ids = [];
            foreach ($query->getParameters() as $parameter) {
                array_push($ids, (int)$parameter->getValue());
            }

            $conn = $this->getDoctrine()->getConnection();
            $from = $query->getDqlParts()['from'][0];
            $alias = $from->getAlias() ?? 'o';
            $sql = 'UPDATE page AS '.$alias.' SET '.$alias.'.status = -1 ';
            $log_sql = 'select '.$alias.'.title from page as '.$alias.' ';
            if ($ids) {
                $sql .= 'WHERE '.$alias.'.id IN ('.implode(",", $ids).')';
                $log_sql .= 'WHERE '.$alias.'.id IN ('.implode(",", $ids).')';
            } else {
                // 获取查询条件
                $where = $query->getDqlParts()['where'];
                if ($where->getParts()) {
                    $sql .= 'WHERE '.implode(' AND ', $where->getParts());
                    $log_sql .= 'WHERE '.implode(' AND ', $where->getParts());
                }
            }
            $stmt = $conn->prepare($sql);
            $stmt->execute();
            $this->addFlash('sonata_flash_success', $this->trans('flash_batch_delete_success', [], 'SonataAdminBundle'));

            // 更新日志
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->execute();
            $pages = $log_stmt->fetchAll();
            foreach ($pages as $page) {
                $description = '标题:['.$page['title'].'] ';
                LogHelper::buildLog(LogTypeEnum::TYPE_PAGE_DELETE, $description);
            }

        } catch (ModelManagerException $e) {
            $this->handleModelManagerException($e);
            $this->addFlash('sonata_flash_error', $this->trans('flash_batch_delete_error', [], 'SonataAdminBundle'));
        }

        return $this->redirectToList();
    }
}
